import Vue from 'vue';
import Tools from 'utils/tools'
/**
 * 12341234 -> 12,341,234
 */
Vue.filter('numberWithComma', (number) => {
  let parsedNumber = parseFloat(number);
  if (isNaN(parsedNumber)) {
    console.warn(`filter "numberWithComma":value ${number} cannot be parsed`);
    return 0;
  }
  return parsedNumber.toLocaleString();
});

/**
 * 日期格式化
 */
Vue.filter('date', function (time, formatStr) {
  if (typeof time == 'string') {
    time = time.replace(/-/g, '/');
    time = time.indexOf(",") > 0 ? time.split(",")[0] : time;
  }
  if (time == undefined) {
    return "";
  }
  let date = new Date(time);
  let dateItem = {
    yyyy: function () {
      return date.getFullYear();
    },
    yy: function () {
      return dateItem.yyyy().slice(-2);
    },
    
    MM: function () {
      return fixZero(dateItem.M());
    },
    /**
     * @return {number}
     */
    M: function () {
      return date.getMonth() + 1;
    },
    
    dd: function () {
      return fixZero(dateItem.d());
    },
    d: function () {
      return date.getDate();
    },
    
    HH: function () {
      return fixZero(dateItem.H());
    },
    /**
     * @return {number}
     */
    H: function () {
      return date.getHours();
    },
    
    hh: function () {
      return fixZero(dateItem.h());
    },
    h: function () {
      return date.getHours() % 13;
    },
    tt: function () {
      return dateItem.H() < 12 ? "am" : "pm";
    },
    /**
     * @return {string}
     */
    TT: function () {
      return dateItem.H() < 12 ? "AM" : "PM";
    },
    
    mm: function () {
      return fixZero(dateItem.m());
    },
    m: function () {
      return date.getMinutes();
    },
    
    ss: function () {
      return fixZero(dateItem.s());
    },
    s: function () {
      return date.getSeconds();
    }
  };
  let fixZero = function (num) {
    return (num + '').length < 2 ? ('0' + num) : num;
  };
  for (let s in dateItem) {
    formatStr = formatStr.replace(s, dateItem[s]);
  }
  return formatStr;
});

/**
 * 大于万的数字以万为单位
 */
Vue.filter('byTenThousands', (num) => {
  let number = parseFloat(num);
  if (isNaN(number)) return 0;
  if (number < 10e3) return number;
  return `${parseInt(number / 10000)}.${parseInt(number % 10000 / 1000)}万`;
});

/**
 * 文字打码
 */
Vue.filter('string*ify', (string, keepStart = 3, keepEnd = 3, symbol = '*') => {
  return Tools.stringEncrypt(string, keepStart, keepEnd , symbol)
});

/**
 * gif动起来
 */
Vue.filter('recoverGif', (url) => {
  if (url.indexOf('.gif?') > 0) {
    url = url.substr(0, url.indexOf('.gif?') + 4)
  }
  return url;
});